import numpy as np
import matplotlib.pyplot as plt
import io
from scipy import signal
import ast
from decimal import Decimal


plt.ion()
#fig,ax=plt.subplots(figsize=(15,7.5))
SourceAll = []
#频谱
def draw_fft(SF,NFFT):
    print("-------SF,NFFT--------")
    print(SF,NFFT)
    SR = int(NFFT) #发射频率
    #NFFT = 512 #source的长度
    Phs = 0                             #phase
    NFFT_calc = int(NFFT/2) + 1                      #number of freqeuncies 频率数
    #f = SR/2*np.linspace(0,1,NFFT_calc)    #frequencies 频率
    Delta_T = 1/SR                      #sampling interval
    A = 1                               #mag
    t = np.arange(0, NFFT, 1)*Delta_T    #Time vector
    source = A * signal.square(2*np.pi*SF*t + Phs, duty=0.5)      # square wave
    FFT =  2 * np.fft.fft(source, n=NFFT)/NFFT
    f = SR/2*np.linspace(0,1,NFFT_calc)    #frequencies

    plt.figure(figsize=(24,8))
    plt.loglog(f,np.abs(FFT[0:NFFT_calc]), 'red')
    plt.title('Simple Scatterplot')
    plt.ylabel('Amplitude')
    plt.xlabel('Frequency(Hz)')
    plt.ylim([0.00001,10])
    #indx = np.where(f == SF)
    # print('Mag at fundemental is', np.abs(FFT[indx])[0])
    fio = io.BytesIO()
    plt.savefig(fio, format="png")
    return fio.getvalue()
#方波
# def draw_fft_square_wave(data,SF,NFFT):
#     s = data
#     s = s[1:-1]
#     source = [float(n) for n in s.split(',')]
#
#     fs = 200.0  # Sample frequency (Hz)
#     f0 = 60.0  # Frequency to be removed from signal (Hz)
#     Q = 30.0  # Quality factor
#     # Design notch filter
#     b, a = signal.iirnotch(f0, Q, fs)
#     freq, h = signal.freqz(b, a, fs=fs)
#
#     SR = 1000 #发射频率
#     Delta_T = 1/SR                      #sampling interval 采样间隔
#     t = np.arange(0, NFFT, 1)*Delta_T    #Time vector 时间向量
#     plt.figure(figsize=(24,8))
#     print(len(source))
#     print(len(freq))
#     plt.plot(t, source, 'green')
#     #plt.plot(freq, source, 'green')
#     plt.ylabel('Amplitude')
#     plt.xlabel('Time (s)')
#     plt.ioff()
#     f = io.BytesIO()
#     plt.savefig(f, format="png")
#     return f.getvalue()
#方波
def draw_fft_square_wave(data,SF,NFFT,filter):

    # s = data
    # s = s[1:-1]
    # source = [Decimal(n) for n in s.split(',')] #str转Decimal
    SR = NFFT
    if SF == '8' or SF == '4' or SF == '2'or SF == '1':
        SF = int(SF)
    elif SF == '1/2':
        SF = 0.5
    elif SF == '1/4':
        SF = 0.25
    elif SF == '1/8':
        SF = 0.125

    print("====================== SF ======================="+str(SF))
    print("====================== NFFT ======================="+str(NFFT))
    print("======================filter======================="+str(filter))
    source = []
    filtedData = []
    fs = 1000  # 采样频率
    list_float = data.strip(',').split(",")
    for i in range(len(list_float)):
        # data2 = Decimal(list_float[i])
        data2 = list_float[i]
        #print(data2)
        source.append(float(data2))
    if filter == 1:#低频滤波
        # b, a  =   signal.butter( 50 ,  50 ,  'lowpass' )    #配置滤波器 8 表示滤波器的阶数
        # filtedData  =   signal.filtfilt(b, a, source)   #source为要过滤的信号
        # 设计陷波滤波器来去除50 Hz干扰
        f0 = 50.0  # 噪声的中心频率
        Q = 30.0  # 带宽
        b, a = signal.iirnotch(f0, Q, fs)
        filtedData = signal.filtfilt(b, a, source)
    elif filter == 2:
        b, a  =   signal.butter( 8 , [0.1,0.12],  'bandstop' )    #配置滤波器 8 表示滤波器的阶数
        filtedData  =   signal.filtfilt(b, a, source)   #source为要过滤的信号
    else:
        filtedData = source

    #FFT转化
    # FFT =  2 * np.fft.fft(filtedData, n=NFFT)/NFFT
    # NFFT_calc = int(NFFT/2) + 1
    # f = SR/2*np.linspace(0,1,NFFT_calc)    #frequencies
    # plt.plot(f,np.abs(FFT[0:NFFT_calc]), 'green')#FFT处理
    # plt.ylim(-0.025, 0.025)

    #原始数据未FFT处理
    Delta_T = 1/SR                      #sampling interval间隔
    t = np.arange(0, NFFT, 1)*Delta_T    #Time vector
    plt.figure(figsize=(15, 7.5))
    plt.plot(t, filtedData, 'green')
    plt.ylabel('Amplitude')
    plt.xlabel('Time (s)')
    #plt.ylim(-0.1, 0.1)
    plt.ioff()
    fsq = io.BytesIO()
    plt.savefig(fsq, format="png")
    plt.close()
    fio = fsq.getvalue()
    fsq.close()
    return fio

#极化率
def polarizabilityold(rx_v,tx_c):

    # list_rx_v = []
    # list_rx_v.append(float(rx_v))

    # list_float = rx_v.strip(',').split(",")
    # for i in range(len(list_float)):
    #     list_rx_v.append(float(list_float[i]))

    # list_tx_c = []
    # list_tx_c.append(float(tx_c))

    # list_float = rx_v.strip(',').split(",")
    # for i in range(len(list_float)):
    #     list_tx_c.append(float(list_float[i]))

    # fft_rxv =  np.angle(float(rx_v))
    # fft_txc =  np.angle(float(tx_c))
    fft_rxv = Decimal("%.5f" %float(rx_v))*Decimal(100000)
    fft_txc = Decimal("%.5f" %float(tx_c))*Decimal(100000)
    sub_rvtv = fft_rxv - fft_txc
    data = (sub_rvtv/100000/Decimal("%.5f" % np.pi))*Decimal(180)
    # print(type(data))
    #print(Decimal("%.5f" % data))

    #strData = str(data).replace('[','').replace(']','').rstrip(".")
    strData = str(Decimal("%.5f" % data))
    return  strData
#极化率
def polarizability(xv,xv1):
    """
    XV 供电时的总电位差tx_v xv1接收电压
    """
    fft_xv = Decimal("%.5f" %float(xv))*Decimal(100)
    fft_xv1 = Decimal("%.5f" %float(xv1))
    sub_pol = fft_xv1 / fft_xv * 100
    strData = str(Decimal("%.5f" %sub_pol))
    return  strData

def jb2pb(byte_arr):
    """
    java 字节码转python字节码
    :return:
    """
    return [i + 256 if i < 0 else i for i in byte_arr]